package com.yuelao.yuelao_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuelao.yuelao_backend.common.BizException;
import com.yuelao.yuelao_backend.common.ErrorCode;
import com.yuelao.yuelao_backend.dto.ShopItemDTO;
import com.yuelao.yuelao_backend.dto.UserItemDTO;
import com.yuelao.yuelao_backend.entity.ShopItem;
import com.yuelao.yuelao_backend.entity.User;
import com.yuelao.yuelao_backend.entity.UserItem;
import com.yuelao.yuelao_backend.mapper.ShopItemMapper;
import com.yuelao.yuelao_backend.mapper.UserItemMapper;
import com.yuelao.yuelao_backend.service.AchievementService;
import com.yuelao.yuelao_backend.service.CoinService;
import com.yuelao.yuelao_backend.service.ShopService;
import com.yuelao.yuelao_backend.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import jakarta.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ShopServiceImpl extends ServiceImpl<ShopItemMapper, ShopItem> implements ShopService {

    @Resource
    private UserItemMapper userItemMapper;

    @Resource
    private UserService userService;

    @Resource
    private CoinService coinService;
    
    @Resource
    private AchievementService achievementService;

    @Override
    public UserItemDTO convertToUserItemDTO(UserItem userItem) {
        if (userItem == null) {
            return null;
        }
        UserItemDTO dto = new UserItemDTO();
        BeanUtils.copyProperties(userItem, dto);
        // 填充商品信息
        ShopItem shopItem = getById(userItem.getItemId());
        if (shopItem != null) {
            dto.setItemName(shopItem.getName());
            dto.setItemDescription(shopItem.getDescription());
            dto.setItemImageUrl(shopItem.getImage());
            dto.setItemCategory(shopItem.getCategory());
        }
        return dto;
    }

    public List<ShopItemDTO> getShopItems(String category) {
        LambdaQueryWrapper<ShopItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopItem::getStatus, 1);
        if (StringUtils.hasText(category)) {
            queryWrapper.eq(ShopItem::getCategory, category);
        }
        List<ShopItem> shopItems = list(queryWrapper);
        return shopItems.stream()
                .map(this::convertToShopItemDTO)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public boolean purchaseItem(Long userId, Long itemId, Integer quantity) {
        if (quantity <= 0) {
            throw new BizException(ErrorCode.PARAMS_ERROR, "购买数量必须大于0");
        }

        ShopItem item = getById(itemId);
        if (item == null || 1!=item.getStatus()) {
            throw new BizException(ErrorCode.NOT_FOUND_ERROR, "商品不存在或已下架");
        }
        if (item.getStock() != null && item.getStock() != -1 && item.getStock() < quantity) {
            throw new BizException(ErrorCode.OPERATION_ERROR, "商品库存不足");
        }

        User user = userService.getById(userId);
        if (user == null) {
            throw new BizException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }

        // 计算总价
        Integer totalPrice = item.getPrice() * quantity;

        // 扣除爱心币或RMB (这里只处理爱心币)
        if ("coin".equals(item.getPriceUnit())) {
            coinService.spendCoins(userId, totalPrice, "shop", "购买商品",
                "购买商品: " + item.getName(), itemId, "shop_item");
        } else {
            // TODO: 处理RMB支付逻辑
            throw new BizException(ErrorCode.OPERATION_ERROR, "暂不支持RMB支付");
        }

        // 增加用户道具
        LambdaQueryWrapper<UserItem> userItemQuery = new LambdaQueryWrapper<>();
        userItemQuery.eq(UserItem::getUserId, userId)
                .eq(UserItem::getItemId, itemId);
        UserItem userItem = userItemMapper.selectOne(userItemQuery);

        if (userItem == null) {
            userItem = new UserItem();
            userItem.setUserId(userId);
            userItem.setItemId(itemId);
            userItem.setQuantity(quantity);
            userItem.setAcquiredAt(LocalDateTime.now());
            userItem.setStatus("active");
            userItemMapper.insert(userItem);
        } else {
            userItem.setQuantity(userItem.getQuantity() + quantity);
            userItemMapper.updateById(userItem);
        }

        // 扣减商品库存
        if (item.getStock() != null && item.getStock() != -1) {
            item.setStock(item.getStock() - quantity);
            updateById(item);
        }

        // 检查商城购买相关成就
        achievementService.checkShopPurchaseAchievements(userId);

        // 检查购买道具相关成就
        if ("prop".equals(item.getCategory())) {
            achievementService.checkBuyItemAchievements(userId);
        }

        return true;
    }

    @Override
    public List<UserItemDTO> getMyItems(Long userId) {
        LambdaQueryWrapper<UserItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserItem::getUserId, userId)
                .eq(UserItem::getStatus, "active"); // 只显示活跃的道具
        List<UserItem> userItems = userItemMapper.selectList(queryWrapper);

        return userItems.stream()
                .map(this::convertToUserItemDTO)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public boolean useItem(Long userId, Long userItemId) {
        UserItem userItem = userItemMapper.selectById(userItemId);
        if (userItem == null || !userItem.getUserId().equals(userId) || !"active".equals(userItem.getStatus())) {
            throw new BizException(ErrorCode.NOT_FOUND_ERROR, "道具不存在或不可用");
        }
        if (userItem.getQuantity() <= 0) {
            throw new BizException(ErrorCode.OPERATION_ERROR, "道具数量不足");
        }

        ShopItem shopItem = getById(userItem.getItemId());
        if (shopItem == null) {
            throw new BizException(ErrorCode.NOT_FOUND_ERROR, "关联商品不存在");
        }

        // 扣减道具数量
        userItem.setQuantity(userItem.getQuantity() - 1);
        if (userItem.getQuantity() == 0) {
            userItem.setStatus("used"); // 数量为0则标记为已用完
        }
        userItemMapper.updateById(userItem);

        // 根据道具类型执行相应逻辑
        switch (shopItem.getCategory()) {
            case "vip":
                // 假设VIP道具增加用户VIP时间
                User user = userService.getById(userId);
                if (user != null) {
                    LocalDateTime newExpireTime = user.getVipExpireTime() != null && user.getVipExpireTime().isAfter(LocalDateTime.now())
                            ? user.getVipExpireTime().plusMonths(1) // 增加一个月
                            : LocalDateTime.now().plusMonths(1);
                    user.setIsVip(true);
                    user.setVipExpireTime(newExpireTime);
                    userService.updateById(user);
                }
                break;
            case "prop":
                // TODO: 处理其他道具逻辑，例如增加魅力值、隐身卡等
                break;
            case "coin_pack":
                // 购买爱心币包，已经在 purchaseItem 中处理了，这里不应该再次触发
                break;
            default:
                throw new BizException(ErrorCode.OPERATION_ERROR, "不支持的道具类型");
        }
        return true;
    }

    @Override
    public ShopItemDTO convertToShopItemDTO(ShopItem shopItem) {
        if (shopItem == null) {
            return null;
        }
        ShopItemDTO dto = new ShopItemDTO();
        BeanUtils.copyProperties(shopItem, dto);
        return dto;
    }
}


